<template>
    <div>
        <el-form :inline="true">
            <el-form-item label="题单名称">
                <el-input placeholder="请输入题单名称" v-model.lazy="like" clearable @keyup.enter="start"></el-input>
            </el-form-item>
            <el-form-item class="">
                <el-button @click="start" :icon="Search" type="primary"> 查询 </el-button>
                <router-link :to="{ name: '添加题单' }" custom v-slot="{ navigate }">
                    <el-button @click="navigate" type="primary">+添加题单</el-button>
                </router-link>
                <el-button @click="funcupdatetop">修改排序</el-button>
            </el-form-item>
        </el-form>
        <div class="row mb-1">
            <div class="col">
                <el-table :data="tableData" border height="80vh" style="width: 100%" @sort-change="sortchange"
                    @cell-click="userhandleCurrentChange ? userhandleCurrentChange : () => { }"
                    @selection-change="handleChange" :highlight-current-row="!!userhandleCurrentChange"
                    @current-change="userCurrentChange">
                    <el-table-column v-if="handleSelectionChange" type="selection" width="55"></el-table-column>
                    <el-table-column v-for="(v, i) in tableu" :key="v.label + i" :prop="v.prop" :label="v.label"
                        :formatter="v.formatter" :sortable="v.sortable"></el-table-column>
                    <el-table-column label="操作" width="300">
                        <template #default="scope">
                            <!-- <el-button type="success" size="default">
            <router-link :to="{ name: '题单', params: { ID: scope.row.ID } }">查看</router-link>
          </el-button> -->
                            <router-link :to="{ name: '添加题单', query: { ID: scope.row.ID } }" custom
                                v-slot="{ navigate }">
                                <el-button type="warning" @click="navigate">修改</el-button>
                            </router-link>
                            <!-- <el-button>答题记录{{ scope.row.userquestioncount }}</el-button> -->
                            <el-button v-if="!tenant_id" @click="del(scope.row.ID)" type="danger">删除</el-button>
                            <el-button plain type="">
                                <a target="_blank" :href="`${pdfBaseUrl}/question.html?questionbankid=${scope.row.ID}&title=${scope.row.name}`"
                                    type="primary">保存题单为pdf</a>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <el-pagination class="pager" :page-size="Number(limit)" :total="count" :page-sizes="pageSizes"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            layout="total ,sizes,prev, pager, next">
        </el-pagination>

        <el-dialog v-model="updatetop" title="Tips" width="700px">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    排序
                </span>
            </template>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <td width="100" class="text-center">ID</td>
                        <td width="100" class="text-center">排序</td>
                        <td class="text-center">名称</td>
                    </tr>
                </thead>
                <vuedraggable tag="tbody" v-model="questionbanks" item-key="ID">
                    <template #item="{ element, index }">
                        <tr>
                            <td>{{ element.ID }}</td>
                            <td>{{ element.top }}</td>
                            <td class="text-center">
                                {{ element.name }}
                            </td>
                        </tr>
                    </template>
                </vuedraggable>
            </table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="updatetop = false">取消</el-button>
                    <el-button type="primary" @click="update">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>


<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElTag } from "element-plus";
import { computed, h, inject, onMounted, ref, watch } from "vue";
import vuedraggable from 'vuedraggable';
import { useStore } from "vuex";
import { Iobj, asynccreateorupdatequestionbank, asyncdelquestionbank, asyncselectlabel, asyncselectquestionbank } from "../../../api/index";
import { Storekey, TtableU } from "../../../interface";
import study from "../../../mysql_interface/studycodemodel";
import { modelFind } from "../../../util/modelkey";
import { toLocaleDateString } from "../../../util/time";
import { LabelType } from '@/util/data';

// 码客行
const tenant_id = inject<string | undefined>('tenant_id', undefined)

const p = defineProps<{
    changelabel?: (l: study.Iuserquestion) => void,
    tablekey?: Array<keyof study.Iquestionbank>,
    handleSelectionChange?: (n: study.Iquestionbank[]) => void,
    selectarr?: number[],
    userhandleCurrentChange?: (n: study.Iquestionbank) => void,
    where?: study.Iquestionbank,
    team?: study.Iteam,
}>()
const pdfBaseUrl = process.env.NODE_ENV === 'production' ? 'https://oj.hterobot.com' : '';

const sortable = ref('DESC')
const offset = ref(0)
const limit = ref(20)
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500]
const order = ref('ID')
const like = ref()
const ID = ref()
const tableu = ref([])
const updatetop = ref(false)

const questionbanks = ref<study.Iquestionbank[]>([])
const _questionbanks = ref<study.Iquestionbank[]>([])
const _tableu: Array<TtableU<study.Iquestionbank>> = [
    {
        label: "ID",
        prop: "ID",
        sortable: true,
    },
    {
        label: "名称",
        prop: "name",
        sortable: true,
    },
    {
        label: "题数",
        prop: "questionquestionbankcount",
    },
    {
        label: "用户ID",
        prop: "userid",
        sortable: true,
    },
    {
        label: "类型",
        prop: "usertype",
        sortable: true,
    },
    {
        label: "标签",
        prop: "label",
        formatter: ({ label }) => {
            if (label?.length) {
                return h('div', { class: 'tag-container' },
                    label.map(l => {
                        const tagName = questionBankLabel.value.find(e => e.ID == l)?.name;
                        return h(ElTag, { type: 'primary', size: 'default', class: "question-intable-label" }, () => tagName || '未知标签');
                    })
                );
            }
            return h('span', '');
        },
    },
    {
        prop: "createdAt",
        label: "创建时间",
        sortable: true,
        formatter: ({ createdAt }) => formatter({ updatedAt: createdAt }),
    },
    {
        label: "答题记录",
        prop: "userquestioncount",
        sortable: true,
    },
];
tableu.value = modelFind(_tableu, p.tablekey);


const tableData = computed(() => {
    return store.state.questionbank?.rows || []
})
const count = computed(() => {
    return store.state.questionbank?.count || 0
})
const store = useStore(Storekey)
onMounted(() => {
    start()
})

const questionBankLabel = ref<study.ILabel[]>([])
async function selectlabel() {
    const { rows, count } = await asyncselectlabel({ type: LabelType.QUESTIONBANK })
    questionBankLabel.value = rows
}

async function start() {
    try {
        let _like: [keyof study.Iquestionbank, string | number] | undefined;
        if (like.value) {
            if (like.value == Number(like.value)) {
                _like = ['ID', like.value]
            } else {
                _like = ['name', like.value]
            }
        }
        const query: Iobj<study.Iquestionbank> = Object.assign(
            p.where ? p.where : {},
            {
                _limit: limit.value,
                _offset: offset.value,
                _order: order.value,
                _sortable: sortable.value,
                _like,
            }
        );
        selectlabel()
        await store.dispatch("actionquestionbank", query);
    } catch (e: any) {
        ElMessage.error(e);
    }
}

function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
}
const handleSizeChange = (val: number) => {
    limit.value = val
    start()
}

async function funcupdatetop() {
    const data = await asyncselectquestionbank({
        usertype: 'public',
        _order: 'top',
        _sortable: 'ASC'
    })
    questionbanks.value = data.rows.map(e => {
        return {
            ID: e.ID,
            name: e.name,
            top: e.top
        }
    })
    _questionbanks.value = data.rows
    updatetop.value = true
}

function sortchange(row: { prop: any; order: any }) {
    const { prop, order } = row;
    if (order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    if (prop) {
        order.value = prop;
    }
}

function formatter({ updatedAt }: any) {
    return toLocaleDateString(updatedAt);
}

function handleChange(data: study.Iquestionbank[]) {
    if (p.handleSelectionChange) p.handleSelectionChange(data);
}

function userCurrentChange(data: study.Iquestionbank) {
    if (p.userhandleCurrentChange) p.userhandleCurrentChange(data);
}

function del(ID: number) {
    try {
        ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
                await asyncdelquestionbank({ ID });
                ElMessage({
                    type: "success",
                    message: "删除成功!",
                });
                start()
            })
            .catch(() => {
                ElMessage({
                    type: "info",
                    message: "已取消删除",
                });
            });

    } catch (e: any) {
        ElMessage({
            message: "删除失败" + e,
            type: "error",
        });
    }
}

async function update() {
    const n = questionbanks.value.map((e, k) => {
        const { top } = _questionbanks.value[k]
        if (top === e.top) {
            return undefined
        }
        return {
            ID: e.ID,
            top,
        }
    }).filter(e => e)
    const c = n.map(e => {
        if (e) {
            return asynccreateorupdatequestionbank(e)
        }
    })
    Promise.all(c).then(() => {
        updatetop.value = false
    })
    ElMessage.success('修改完成')
}

watch(() => offset.value, e => {
    start()
})

</script>